#include <iostream>
#include <list>

#include <QtGui>

#include "invader_menu.h"
#include "invader_label.h"

static const char * const xpm_cursor[] = {
  "6 10 2 1",
  ". c #000000",
  "x c #ffffff",
  "xx....",
  "xx....",
  "xxxx..",
  "xxxx..",
  "xxxxxx",
  "xxxxxx",
  "xxxx..",
  "xxxx..",
  "xx....",
  "xx...."
};

InvaderMenu::InvaderMenu (const QStringList &items, QWidget *parent)
  : QFrame (parent)
{
  _layout = new QGridLayout;
  _layout->setSizeConstraint (QLayout::SetFixedSize);

  QStringList::const_iterator beg = items.begin ();
  QStringList::const_iterator end = items.end ();

  InvaderLabel *l;
  _numItems = 0;
  for (int i = 0; beg != end; ++beg, ++i) {
    l = new InvaderLabel (*beg, this);
    _layout->addWidget (l, i, 1);
    ++_numItems;
  }

  _cursor = new QLabel (this);
  QPixmap p (xpm_cursor);
  _cursor->setPixmap (p);

  _selected = 0;
  _layout->addWidget (_cursor, 0, 0);

  setLayout (_layout);
}

void InvaderMenu::setSelected (unsigned int item)
{
  _selected = item;
  updateCursor ();
}

void InvaderMenu::keyPressEvent (QKeyEvent *event)
{
  switch (event->key ()) {
    case Qt::Key_Up:
      setSelected (_selected - 1);
      emit activity ();
      break;

    case Qt::Key_Down:
      if (_selected + 1 >= _numItems)
        setSelected (0);
      else
        setSelected (_selected + 1);
      emit activity ();
      break;

    case Qt::Key_Return:
    case Qt::Key_Enter:
      emit itemSelected (_selected);
      emit activity ();
      break;

    default:
      emit activity ();
      break;
  }
}

void InvaderMenu::updateCursor ()
{
  if (_selected >= _numItems)
    _selected = _numItems - 1;

  _layout->removeWidget (_cursor);
  _layout->addWidget (_cursor, _selected, 0);
}
